package com.zcs.app.lucky.data

import androidx.lifecycle.MutableLiveData
import cn.sxw.android.base.utils.MMKVUtils
import com.alibaba.fastjson.JSON
import com.zcs.app.lucky.entity.GroupEntity
import com.zcs.app.lucky.entity.LuckyPeople
import com.zcs.app.lucky.isJsonList


object GroupDataCache {
    private const val KEY_GROUP_LIST = "KEY_GROUP_LIST"

    private lateinit var groupList: ArrayList<GroupEntity>
    var tempCheckedId = MutableLiveData<String>()

    fun loadAllGroups(): ArrayList<GroupEntity> {
        val json = MMKVUtils.getString(KEY_GROUP_LIST)
        groupList = if (json.isJsonList()) {
            JSON.parseArray(json, GroupEntity::class.java) as ArrayList<GroupEntity>
        } else {
            ArrayList()
        }
        return groupList
    }

    fun addGroup(group: GroupEntity, isModify: Boolean = false) {
        // 1.如果是修改，先移除上一个
        if (isModify) {
            removeById(group.id)
        }
        // 在首部添加
        groupList.add(0, group)
        notifyGroup()
    }

    private fun notifyGroup() {
        MMKVUtils.put(KEY_GROUP_LIST, JSON.toJSONString(groupList))
    }

    fun findGroupById(id: String): GroupEntity {
        for (group in groupList) {
            if (group.id == id) {
                return group
            }
        }
        return GroupEntity()
    }

    fun findByIdOnNull(id: String): GroupEntity? {
        for (group in groupList) {
            if (group.id == id) {
                return group
            }
        }
        return null
    }

    fun loadUserByGroupId(id: String): ArrayList<LuckyPeople> {
        return findGroupById(id).list
    }

    fun removeById(id: String, notify: Boolean = false) {
        for (g in groupList) {
            if (g.id == id) {
                groupList.remove(g)
                break
            }
        }
        if (notify) notifyGroup()
    }
}
